package org.testile.placeholderscript;

import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

/**
 *
 * @author hvizmar
 */
public class TimeTransformer extends AbstractPatternTransformer {

	private final DateTimeFormatter defaultFormat = DateTimeFormat.forPattern("HH:mm:ss");

	public TimeTransformer() {
		// NOW+1H1M1S
		// NOW-1H1M1S
		super(Pattern.compile("^NOW([+-]([\\d]+H)?([\\d]+M)?([\\d]+S)?)?(@([aKkHhSsm\\-\\\\/: ]*))?$"));
	}

	@Override
	protected String transformMatch(MatchResult match) {
		boolean forward = isInFuture(match.group(1));
		int hours = parseAmount(match.group(2));
		int minutes = parseAmount(match.group(3));
		int seconds = parseAmount(match.group(4));
		DateTime date = forward ? getFutureDate(hours, minutes, seconds) : getPastDate(hours, minutes, seconds);
		DateTimeFormatter format = getFormat(match.group(6));
		return date.toString(format);
	}

	private boolean isInFuture(String plusMinus) {
		return plusMinus != null && plusMinus.startsWith("+");
	}

	private DateTime getFutureDate(int hoursInFuture, int minutesInFuture, int secondsInFuture) {
		DateTime now = new DateTime();
		now = now.plusHours(hoursInFuture);
		now = now.plusMinutes(minutesInFuture);
		now = now.plusSeconds(secondsInFuture);
		return now;
	}

	private DateTime getPastDate(int hoursInPast, int minutesInPast, int secondsInPast) {
		DateTime now = new DateTime();
		now = now.minusHours(hoursInPast);
		now = now.minusMinutes(minutesInPast);
		now = now.minusSeconds(secondsInPast);
		return now;
	}
	
	private int parseAmount(String amountInFuture) {
		if(amountInFuture != null) {
			return Integer.parseInt(amountInFuture.substring(0, amountInFuture.length() - 1));
		}
		return 0;
	}

	private DateTimeFormatter getFormat(String pattern){
		return pattern == null ? defaultFormat : DateTimeFormat.forPattern(pattern);
	}
}
